<template>
    <div class="kefu-container">
    <!-- <h2>客服系统 - 管理端</h2> -->
    
    <el-container class="main-container" style="margin-left:0rpx;">
      <!-- 左侧用户列表 -->
      <el-aside width="280px" class="user-list">
        <!-- 客服信息卡片 -->
        <el-card class="cs-profile">
          <div class="cs-info">
            <el-avatar :size="40" class="cs-avatar">{{ csId.slice(-2) }}</el-avatar>
            <div class="cs-details">
              <div class="cs-name">客服-{{ csId.slice(-4) }}</div>
              <div class="cs-id">{{ csId }}</div>
            </div>
          </div>
          <el-row class="cs-stats" :gutter="20">
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-value">{{ stats.servedCount }}</div>
                <div>今日服务</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-value">{{ stats.avgResponseTime }}s</div>
                <div>平均响应</div>
              </div>
            </el-col>
            <!-- <el-col :span="8">
              <div class="stat-item">
                <div class="stat-value">{{ stats.rating }}</div>
                <div>满意度</div>
              </div>
            </el-col> -->
          </el-row>
        </el-card>

        <!-- 用户列表头部 -->
        <div class="user-list-header">
          <span>在线用户{{ activeUserCount  }}</span>
          <el-tag :type="isConnected || activeUserCount  ? 'success' : 'danger'" size="small">
            {{ isConnected || activeUserCount  ? '已连接' : '断开连接' }}
          </el-tag>
        </div>

        <!-- 等待用户统计 -->
        <div class="waiting-users">
          <span>等待用户：{{ waitingCount }}</span>
        </div>

        <!-- 用户列表 -->
        <div class="users-container">
          <template v-if="Object.keys(chatHistories).length === 0">
            暂无在线用户
          </template>
          <template v-else>
            <div
              v-for="(user, userId) in chatHistories"
              :key="userId"
              class="user-item"
              :class="{ active: activeUserId === userId, unread: unreadUsers.has(userId) }"
              @click="selectUser(userId)"
            >
              <div class="user-info">
                <el-avatar :size="32" class="user-avatar">
                  {{ user.nickname.charAt(0).toUpperCase() }}
                </el-avatar>
                <div class="user-meta">
                  <span class="user-name">{{ user.nickname }}</span>
                  <span class="user-time">{{ formatTime(user.lastMessageTime) }}</span>
                </div>
                <el-tag
                  :type="user.online ? 'success' : 'info'"
                  size="mini"
                  class="user-status"
                >
                  {{ user.online ? '在线' : '离线' }}
                </el-tag>
              </div>
              <el-button
                type="danger"
                size="mini"
                @click.stop="closeSession(userId)"
              >
                结束
              </el-button>
            </div>
          </template>
          <div class="backIcon" v-if="isMobile" @click="closeUserList">
              <i class="el-icon-arrow-left"> </i>
          </div>
        </div>
      </el-aside>

      <!-- 右侧聊天区域 -->
      <el-main class="chat-area">
        
        <div class="chat-header">
          <el-button 
            v-if="isMobile && activeUserId" 
            class="back-button" 
            icon="el-icon-arrow-left" 
            @click="toggleUserList"
          ></el-button>
          <span class="current-chat-title" @click="toggleUserList">
            {{ activeUserId ? `正在与 ${chatHistories[activeUserId].nickname} 对话` : '选择用户开始对话' }}
          </span>
        </div>

        <div class="chat-messages" ref="chatMessages">
          <template v-if="!activeUserId">
            <div >
              请从左侧选择用户开始对话
            </div>
          </template>
          <template v-else>
            <div
              v-for="(message, index) in chatHistories[activeUserId].messages"
              :key="index"
              :class="['message', message.type === 'user' ? 'user-message' : 'cs-message']"
            >
              <div class="message-content">{{ message.message }}</div>
              <span class="message-time">{{ formatTime(message.time) }}</span>
            </div>
          </template>
        </div>

        <div class="reply-area">
          <el-input
            v-model="replyMessage"
            type="textarea"
            :rows="3"
            placeholder="输入回复内容..."
            :disabled="!activeUserId"
            @keyup.enter.native="sendReply"
          />
          <el-button
            type="primary"
            :disabled="!activeUserId || !replyMessage.trim()"
            @click="sendReply"
          >
            发送
          </el-button>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import websocketService from '@/services/websocket'

export default {
  name: 'KefuView',
  data() {
    return {
      csId: localStorage.getItem('userId'),
      maxUsers: 10,
      activeUserId: null,
      replyMessage: '',
      chatHistories: {},
      unreadUsers: new Set(),
      stats: {
        servedCount: 0,
        avgResponseTime: 0,
        rating: 5.0
      },
      isMobile: false,
      showUserList: false
    }
  },
  computed: {
    isConnected() {
      return websocketService.isConnected
    },
    activeUserCount() {
      return Object.values(this.chatHistories).filter(user => user.online).length
    },
    waitingCount() {
      return Object.keys(this.chatHistories).length - this.activeUserCount
    }
  },
  methods: {
    checkMobile() {
      this.isMobile = window.innerWidth <= 500
    },
    toggleUserList() {
      if (!this.isMobile) {
        return
      }
      // console.log('执行了')
      this.showUserList = !this.showUserList
      const userList = document.querySelector('.user-list')
      if (userList) {
        userList.classList.toggle('show', this.showUserList)
      }
    },
    handleWebSocketMessage(data) {
      switch(data.type) {
        case 'session_fullinfo':
          this.handleSessionFullInfo(data.sessions)
          break
        case 'session_history':
          this.handleSessionHistory(data.userId, data.messages)
          break
        case 'history_sync':
          this.handleHistorySync(data.userId, data.messages)
          break
        case 'auth_success':
          this.updateStats(data.stats)
          break
        case 'new_user':
          this.addUser(data.userId, data.nickname)
          break
        case 'user_message':
          this.handleUserMessage(data.userId, data.message, data.time, data.nickname)
          break
        case 'user_leave':
          this.removeUser(data.userId)
          break
        case 'user_reconnect':
          this.updateUserStatus(data.userId, true)
          break
        case 'user_offline':
          this.updateUserStatus(data.userId, false)
          break
        case 'error':
          this.$message.error(data.message)
          break
        case 'system':
          this.showSystemMessage(data.message)
          break
        case 'stats_update':
          this.updateStats(data)
          break
      }
    },
    handleSessionFullInfo(sessions) {
      
      if (Array.isArray(sessions)) {
        sessions.forEach(session => {
        const userId = session.userId
        if (!this.chatHistories[userId]) {
          this.addUser(userId, session.nickname)
        }

        // 更新用户状态
        this.$set(this.chatHistories[userId], 'online', session.status === 'online')

        // 处理历史消息
        if (session.history && session.history.length > 0) {
          this.$set(this.chatHistories[userId], 'messages', session.history.map(msg => ({
            type: msg.type,
            message: msg.message,
            time: msg.time
          })))
        }

        // 更新最后活动时间
        this.$set(this.chatHistories[userId], 'lastMessageTime', session.lastActive)
      })
      }
      

      // 如果有当前选中用户，刷新聊天记录
      if (this.activeUserId && this.chatHistories[this.activeUserId]) {
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }
    },

    handleSessionHistory(userId, messages) {
      if (!this.chatHistories[userId]) {
        this.addUser(userId, messages[0]?.nickname || `用户${userId}`)
      }

      this.$set(this.chatHistories[userId], 'messages', messages.map(msg => ({
        type: msg.type === 'user' ? 'user' : 'cs',
        message: msg.message,
        time: msg.time
      })))

      if (this.activeUserId === userId) {
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }
    },

    handleHistorySync(userId, messages) {
      if (this.chatHistories[userId]) {
        this.$set(this.chatHistories[userId], 'messages', messages)
        if (this.activeUserId === userId) {
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }
      }
    },

    handleUserMessage(userId, message, timestamp, nickname) {
      if (!this.chatHistories[userId]) {
        // 新增离线用户处理
        this.addUser(userId, nickname)
        this.$set(this.chatHistories[userId], 'online', false)
      }

      // 存储消息
      const messageObj = {
        type: 'user',
        message: message,
        time: timestamp || Math.floor(Date.now() / 1000)
      }

      if (!this.chatHistories[userId].messages) {
        this.$set(this.chatHistories[userId], 'messages', [])
      }
      this.chatHistories[userId].messages.push(messageObj)
      this.$set(this.chatHistories[userId], 'lastMessageTime', messageObj.time)

      // 如果是当前活跃用户，直接显示
      if (this.activeUserId === userId) {
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      } else {
        // 标记为未读
        this.unreadUsers.add(userId)
      }

      // 如果有新消息通知权限，可以在这里添加
      if (Notification.permission === 'granted' && document.hidden) {
        new Notification(`新消息来自 ${this.chatHistories[userId].nickname}`, {
          body: message.length > 50 ? `${message.substring(0, 50)}...` : message
        })
      }
    },

    updateUserStatus(userId, isOnline) {
      if (!this.chatHistories[userId]) return

      this.$set(this.chatHistories[userId], 'online', isOnline)

      if (!isOnline && this.activeUserId === userId) {
        this.$message.info('用户已离线')
      }
    },

    showSystemMessage(message) {
      if (this.activeUserId && this.chatHistories[this.activeUserId]) {
        const systemMessage = {
          type: 'system',
          message: message,
          time: Math.floor(Date.now() / 1000)
        }
        this.chatHistories[this.activeUserId].messages.push(systemMessage)
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }
    },

    addUser(userId, nickname) {

      if (!this.chatHistories[userId]) {
        this.$set(this.chatHistories, userId, {
          nickname: nickname || `用户${userId}`,
          online: true,
          messages: [],
          responseStart: Date.now()
        })
      }
    },

    removeUser(userId) {
      if (this.chatHistories[userId]) {
        this.chatHistories[userId].online = false
        delete this.chatHistories[userId]
      }
      this.unreadUsers.delete(userId)

      if (this.activeUserId === userId) {
        this.activeUserId = null
        this.replyMessage = ''
      }
    },
    closeUserList() {
      if (this.isMobile) {
        this.showUserList = false
        const userList = document.querySelector('.user-list')
        if (userList) {
          userList.classList.remove('show')
        }
      }
    },
    selectUser(userId) {
      const userData = this.chatHistories[userId]
      if (!userData) return

      this.activeUserId = userId
      this.unreadUsers.delete(userId)

      if (userData.responseStart) {
        const responseTime = Date.now() - userData.responseStart
        this.stats.avgResponseTime = Math.round(responseTime / 1000)
        delete userData.responseStart
      }

      if (this.isMobile) {
        this.showUserList = false
        const userList = document.querySelector('.user-list')
        if (userList) {
          userList.classList.remove('show')
        }
      }

      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },

    sendReply() {
      if (!this.activeUserId || !websocketService.isConnected) {
        this.$message.error('连接不可用，请检查网络')
        return
      }

      const message = this.replyMessage.trim()
      if (message) {
        websocketService.send({
          command: 'cs_reply',
          userId: this.activeUserId,
          message: message
        })

        const messageObj = {
          type: 'cs',
          message: message,
          time: Math.floor(Date.now() / 1000)
        }

        this.chatHistories[this.activeUserId].messages.push(messageObj)
        this.replyMessage = ''

        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }
    },

    closeSession(userId) {
      this.$confirm(`确定要结束与 ${this.chatHistories[userId]?.nickname || '用户'} 的会话吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        websocketService.send({
          command: 'close_session',
          userId: userId,
          csId: this.csId
        })
        this.removeUser(userId)
      }).catch(() => {})
    },

    updateStats(stats) {
      if (stats.servedCount) this.stats.servedCount = stats.servedCount
      if (stats.avgResponseTime) this.stats.avgResponseTime = stats.avgResponseTime
      if (stats.rating) this.stats.rating = stats.rating
    },

    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp * 1000)
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
      })
    },

    scrollToBottom() {
      const container = this.$refs.chatMessages
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    }
  },
  mounted() {
    this.checkMobile()
    window.addEventListener('resize', this.checkMobile)
    
    if (localStorage.getItem('reloadKefu')) {
      localStorage.removeItem('reloadKefu')
      window.location.reload()
    }
    websocketService.addMessageHandler(this.handleWebSocketMessage)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.checkMobile)
    websocketService.removeMessageHandler(this.handleWebSocketMessage)
  }
}
</script>

<style scoped>
.kefu-container {
  padding: 20px;
  /* height: 100vh; */
  background-color: #f9f9f9;
}

.main-container {
  /* height: calc(100vh - 400px); */
  height: 800px !important;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.user-list {
  border-right: 1px solid #ddd;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.cs-profile {
  margin-bottom: 10px;
}

.cs-info {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.cs-details {
  margin-left: 10px;
}

.cs-name {
  font-weight: bold;
}

.cs-id {
  font-size: 0.8em;
  color: #777;
}

.cs-stats {
  text-align: center;
}

.stat-item {
  padding: 5px;
}

.stat-value {
  font-weight: bold;
  color: #409EFF;
}

.user-list-header {
  padding: 15px;
  background: #409EFF;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.waiting-users {
  padding: 10px 15px;
  background: #f0f0f0;
  font-size: 14px;
}

.users-container {
  flex: 1;
  overflow-y: auto;
  /* position: relative; */
}
.backIcon {
  position: absolute;
  background-color: #ffffff;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: 30px;
  color: #000000;
  right: 0px;
  top: calc(50% - 15px);
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  
}

.user-item {
  padding: 12px 15px;
  cursor: pointer;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: background-color 0.2s;
}

.user-item:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.user-item.active {
  background-color: #e3f2fd;
  border-left: 3px solid #409EFF;
}

.user-item.unread::after {
  content: "";
  display: inline-block;
  width: 8px;
  height: 8px;
  background-color: #F56C6C;
  border-radius: 50%;
  margin-left: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.user-meta {
  margin-left: 10px;
  flex: 1;
}

.user-name {
  font-weight: 500;
}

.user-time {
  font-size: 12px;
  color: #777;
}

.chat-area {
  display: flex;
  flex-direction: column;
  padding: 0;
}

.chat-header {
  padding: 15px;
  border-bottom: 1px solid #ddd;
  background: white;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: white;
}

.message {
  margin-bottom: 15px;
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 18px;
  position: relative;
  word-wrap: break-word;
  animation: fadeIn 0.3s ease-out;
}

.user-message {
  background: #e3f2fd;
  margin-right: auto;
  border-bottom-left-radius: 5px;
}

.cs-message {
  background: #f0f4c3;
  margin-left: auto;
  border-bottom-right-radius: 5px;
}

.message-time {
  font-size: 0.75rem;
  color: #777;
  margin-top: 5px;
}

.reply-area {
  padding: 15px;
  border-top: 1px solid #ddd;
  background: #f5f5f5;
  display: flex;
  gap: 10px;
}

.reply-area .el-button {
  align-self: flex-end;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 移动端样式 */
@media screen and (max-width: 500px) {
  .kefu-container {
    padding: 10px;
  }

  .main-container {
    height: calc(100vh - 70px) !important;
    border-radius: 4px;
  }

  .user-list {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    width: 100%;
    z-index: 10;
    transform: translateX(-100%);
    transition: transform 0.3s ease;
  }

  .user-list.show {
    transform: translateX(0);
  }

  .chat-area {
    width: 100%;
  }

  .chat-header {
    padding: 10px;
    display: flex;
    align-items: center;
  }

  .chat-header .back-button {
    margin-right: 10px;
    display: block;
  }

  .chat-messages {
    padding: 10px;
  }

  .message {
    max-width: 85%;
  }

  .reply-area {
    padding: 10px;
  }

  .reply-area .el-button {
    padding: 8px 15px;
  }

  .cs-profile {
    margin-bottom: 5px;
  }

  .user-list-header {
    padding: 10px;
  }

  .user-item {
    padding: 8px 10px;
  }
}
</style> 